package com._21cn._front.product.page.pc;

import com._21cn._front.GenerateHandler;
import com._21cn._front.product.page.label.WatchLabel;
import com._21cn.cms.common.ErrorCode;
import com._21cn.cms.common.obj.ResponseObj;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;
import com._21cn.cms.template.utils.TemplateHelper;
import com._21cn.cms.template.utils.label.RegionObjLabel;
import com._21cn.cms.template.utils.label.ToolsLabel;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.product.entity.Watch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/11/28.
 */
@Component("pcWatchPageContent")
public class PcWatchPageContent implements GenerateHandler {

    private static Pattern pattern = Pattern.compile("(/watch/pc/(\\d+).shtml$)");
    private static Integer templateId = 52;
    private static String templateContent = "";

    @Autowired(required = false)
    private WatchLabel watchLabel;

    @Autowired
    private ToolsLabel toolsLabel;

    @Autowired
    private RegionObjLabel regionObjLabel;

    @Autowired
    private TemplateService templateService;

    @Override
    public ResponseObj generate(HttpServletRequest request) {
        ResponseObj responseObj = new ResponseObj();

        try{
            Matcher regexpMatcher = pattern.matcher(request.getRequestURL());
            if (regexpMatcher.find()) {
                String idStr = regexpMatcher.group(2);
                Watch watch = this.watchLabel.getWatch(idStr);
                Map maps = new HashMap();
                maps.put("watch", watch);
                maps.put("toolsLabel", this.toolsLabel);
                maps.put("regionObjLabel", this.regionObjLabel);
                Template template = templateService.getById(templateId);
                templateContent = template.getContent();
                String content = TemplateHelper.evaluateTemplate( templateContent, maps );
                responseObj.setErrorCode(ErrorCode.SUCCESS_CODE);
                responseObj.setMessage(content);
            }
        }catch (Exception e){
            responseObj.setErrorCode(ErrorCode.ERROR_SERVER_EXCEPTION);
            responseObj.setMessage("生成页面异常");
        }

        return responseObj;
    }
}
